<template>
  <div style="padding: 10px;width: 100%">
    <!--  功能区   -->
    <div style="margin: 10px 0;border: 0px solid">
      <el-button type="primary" size="normal" @click="add">新增记录</el-button>
      <el-button type="primary" size="normal" @click="addJournal">新增日志</el-button>
      <el-button type="primary"  size="normal"  @click="yesterdayLoad">前一天</el-button>
      <el-button type="primary"  size="normal"  @click="tomorrowLoad">后一天</el-button>
      过去30天平均：{{getAvg}}小时,{{getAvg*60}}分钟,{{(getAvg*2.4).toFixed(1,2)}}番茄
    </div>
    <div style="border: 0px yellow;width: 100%;display: flex">
      <div style="border: 0px solid red;width: 35%">
        <div style="border: 0px solid">
          <div style="width: 100%;font-weight: bold" >当日总计：{{sum}}分钟&emsp;&emsp;{{sum/25}}番茄</div>
          <div>
            <tr v-for="item in statistic" :key="item.project">
              <td style="padding-right: 30px"> {{item.type}}</td>
              <td style="padding-right: 30px"> {{item.project}}</td>
              <td style="padding-right: 30px"> {{item.duration}}分钟</td>
              <!--              <td style="padding-right: 10px"> {{item.duration/25}}番茄</td>-->
            </tr>
          </div>
        </div>


        <!--  搜索区   -->
        <div style="margin: 10px 0;padding-left: 10px" size="normal">
          <el-date-picker
              v-model="date"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择一天"
              size="normal"
              style="width: 150px;"
          />
          <el-input v-model="search" placeholder="请输入关键字" style="margin-left: 5px;width: 30%" size="normal" clearable/>
          <el-button type="primary" style="margin-left: 5px" size="normal"  @click="load">搜索</el-button>
        </div>
      </div>
      <div id="rightTopBox" style="width: 60%;max-height: 135px;border: 0px solid cyan;margin-left: 30px;display: flex;flex-wrap:wrap;overflow:hidden;align-content: flex-start">
        <!--          {{doingTasks}}-->
        <div v-for="item in doingTasks" :key="item.id" style="width: 350px;border: blue;overflow:hidden;margin: 0;">
          <div style="display: flex;width: 350px;border: 0px solid salmon">
            <div style="border: 0px solid chartreuse;margin-right: 5px">
              <el-button  size="small"   @click="finish(item.id)">√</el-button>
            </div>
            <div style="border: 0px solid green;width: 200px">
              {{item.name}}
            </div>
          </div>
        </div>
      </div>

    </div>



    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="ID" sortable width="70px" v-if="false"/>
      <el-table-column prop="user" label="用户"  v-if="false"/>
      <el-table-column prop="dateTime" label="日期时间"  width="100px"  />
      <el-table-column prop="dayOfWeek" label="星期"   width="50px" />
      <el-table-column prop="type" label="类型"  width="150px" />
      <el-table-column prop="project" label="项目"  width="200px" />
      <el-table-column prop="detail" label="详情"  width="400px"  />
      <el-table-column prop="duration" label="持续时间"  width="80px"  >
        <template #default="scope">
          {{scope.row.duration}}分钟
        </template>
      </el-table-column>
      <el-table-column prop="reportContent" label="周报内容"  width="200px"  />
      <!--      <el-table-column prop="comment" label="注释" width="100px" />-->

      <el-table-column fixed="right" label="Operations" >
        <template #default="scope">
          <el-button  size="small"  @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确认删除吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button size="small"  type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination
          :current-page="currentPage4"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" title="新增记录" width="50%">
      <el-form  :model="form" label-width="120px">

        <el-form-item label="类型" style="width: 80%;">
          <el-autocomplete
              v-model="form.type"
              :fetch-suggestions="querySearch"
              clearable
              placeholder="请输入类型"
              @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="项目" style="width: 80%;">
          <el-input v-model="form.project"  />
        </el-form-item>
        <el-form-item label="详情" style="width: 80%;">
          <el-input type="textarea" v-model="form.detail" />
        </el-form-item>
        <el-form-item label="周报内容" style="width: 80%;">
          <el-input type="textarea" v-model="form.reportContent"  />
        </el-form-item>
        <el-form-item label="注释" style="width: 80%;">
          <el-input v-model="form.comment"  />
        </el-form-item>
        <el-form-item label="持续时间(分钟)" style="width: 80%;">
          <el-input v-model="form.duration" type="number"  />
        </el-form-item>
        <el-form-item label="时间" style="width: 80%;">
          <el-date-picker
              v-model="form.dateTime"
              type="datetime"
              placeholder="选择日期和时间"
              :shortcuts="shortcuts"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <ul v-for="item in journals" style="border: 0px solid;margin-left: 10px;width: 90%">
      <p style="white-space:pre-wrap">{{item.content}}</p><br/>
    </ul>

    <el-dialog v-model="journalDialogVisible" title="新增日志" width="50%">
      <el-form ref="journalForm" :model="journalForm" label-width="120px" :rules="journalRules">
        <el-form-item label="内容" style="width: 80%" prop="journalForm.content">
          <el-input type="textarea" v-model="journalForm.content" :maxlength="500" :autosize="{ minRows: 10, maxRows: 10}" />
        </el-form-item>
        <el-form-item label="注释" style="width: 80%;">
          <el-input v-model="journalForm.comment"  />
        </el-form-item>
        <el-form-item label="权限" style="width: 80%;">
          <el-select v-model="journalForm.privilege" placeholder="请选择权限" >
            <el-option label="公开" value="open"/>
            <el-option label="私人" value="private"/>
          </el-select>
        </el-form-item>
        <el-form-item label="时间" style="width: 80%;">
          <el-date-picker
              v-model="journalForm.dateTime"
              type="datetime"
              placeholder="选择日期"
              :shortcuts="shortcuts"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="journalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveJournal()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script>


import request from "@/utils/request";
import moment from 'moment';
import * as echarts from "echarts";

export default {
  name: 'LogView',
  components: {
  },
  data(){
    return{
      method: 'sum',
      journalDialogVisible:false,
      doingTasks:[],
      journals:null,
      form:{},
      user:{},
      dialogVisible:false,
      total:11,
      currentPage4:1,
      pageSize:20,
      search:"",
      statistic:"",
      handleSelect:"",
      sum:0,
      typeList:[],
      projectList:[],
      date: new Date(),
      sumOfTime:0,
      tableData: [],
      shortcuts : [
        {text: '今天', value: new Date(),},
        {text: '昨天', value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            return date
          },
        },
        {text: '一周前', value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            return date
          },
        },
      ],
      journalRules:{
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
        ]
      },
      journalForm:{},
    }
  },
  computed: {
    getDay(){
      let end  = moment(this.endDate)
      let begin =moment(this.beginDate)
      let timeDiff = Math.abs(end-begin)
      let diffDays = Math.ceil(timeDiff/(1000 * 60 * 60 *24))
      return diffDays+1
    },
    getHours(){
      let res  = this.sumOfTime/60
      return res.toFixed(1)
    },
    getAvg(){
      let res  = this.getHours/this.getDay
      return res.toFixed(2)
    },
  },
  created(){
    console.log("登录")
    let userStr= sessionStorage.getItem("user") || "{}"
    let user = JSON.parse(userStr)
    this.user=user;
    this.endDate = new moment(new Date()).format("YYYY-MM-DD")
    //起始日期为7天前
    let date = new Date()
    let lastDate = date.getTime() - 3600 * 1000 * 24 * 29
    this.beginDate = new moment(lastDate).format("YYYY-MM-DD")
    console.log("登录1")
    this.load();

  },
  methods:{
    load(){
      console.log("加载load开始")
      //加载信息
      request.get("/log",{
        params:{
          username:this.user.username,
          pageNum:this.currentPage4,
          pageSize:this.pageSize,
          search:this.search,
          date:this.date
        }
      }).then(res =>{
        console.log("加载log...完毕")
        console.log("时间："+this.date)
        this.tableData = res.data.records
        this.total = res.data.total;
      })
      //得到统计信息
      request.get("/log/statistic",{
        params:{
          date:this.formattedDate(),
          username:this.user.username
        }
      }).then(res =>{
        console.log("加载statistic...完毕")
        console.log("时间："+this.formattedDate())
        this.sum = res.data.sum;
        this.statistic = res.data.logs;
      })
      //查询当天的全部日志
      request.get("/journal/oneday",{
        params:{
          username:this.user.username,
          date:this.formattedDate()
        }
      }).then(res =>{
        console.log("加载journal...完毕")
        console.log("时间："+this.formattedDate())
        this.journals = res.data
      })
      //查询待办的任务
      //查询当天的全部日志
      request.get("/task/getTaskByUserAndStatus",{
        params:{
          username:this.user.username,
        }
      }).then(res =>{
        console.log("加载task...完毕")
        this.doingTasks = res.data
      })
      //加载信息
      request.get("/report/getReport",{
        params:{
          username:this.user.username,
          beginDate:this.beginDate,
          endDate:this.endDate,
          method:this.method,
        }
      }).then(res =>{
        if(res.code==0){
          this.res = res.data.sum
          this.typeDuration = res.data.typeDuration
          this.sumOfTime = res.data.sumOfTime
          console.log("sunOfTime:",this.sumOfTime)

        }else{
          this.$message.error(res.msg);
        }
      })
    },
    add(){
      request.get("/log/getTypeAndProject",{
        params:{
          username:this.user.username,
        }
      }).then(res =>{
        console.log("得到用户的类型和项目名")
        this.typeList = res.data.typeList
        this.projectList = res.data.projectList
        console.log(this.typeList)
        console.log(this.projectList)
      })

      this.dialogVisible=true;
      // this.form={};//清空一下表单域
      this.form.id=null;
      this.form.duration=25;
      this.form.dateTime=this.date;
    },
    save(){
      this.form.user=this.user.username
      if(this.form.id){ //更新
        request.put("/log",this.form).then(res =>{
          console.log(res)
          if(res.code==0){
            this.$message.success("更新成功");
            this.dialogVisible=false;
            this.load();
          }else{
            this.$message.error(res.msg);
          }
        })
      }else{ //新增
        request.post("/log",this.form).then(res =>{
          console.log(res)
          if(res.code==0){
            this.$message.success("新增成功");
            this.dialogVisible=false;
            this.load();
          }else{
            this.$message.error(res.msg);
          }
        })
      }

    },
    handleEdit(row){
      this.form = JSON.parse(JSON.stringify(row)) //深度拷贝
      this.dialogVisible=true;
    },
    handleDelete(id){
      console.log(id)
      request.delete("/log/"+id).then(res =>{
        console.log(res)
        if(res.code==0){
          this.$message.success("删除成功");
          this.load();
        }else{
          this.$message.error(res.msg);
        }
      })
    },
    handleSizeChange(pageSize){ //改变当前每页的个数
      this.pageSize=pageSize;
      this.load();
    },
    handleCurrentChange(pageNum){//改变当前页码
      this.currentPage4=pageNum;
      this.load();
    },
    addJournal(){
      this.journalDialogVisible=true;
      this.journalForm.privilege='open'
    },
    finish(row){
      request.get("/task/done",{
        params:{
          id:row,
        }
      }).then(res =>{
        console.log(res)
        if(res.code==0){
          this.$message.success("更新状态成功");
          this.load();
        }else{
          this.$message.error(res.msg);
        }
      })
    },
    saveJournal(){
      this.$refs['journalForm'].validate(valid=> {
        if (valid) {
          this.journalForm.user=this.user.username
          request.post("/journal",this.journalForm).then(res =>{
            console.log(res)
            if(res.code==0){
              this.$message.success("新增成功");
              this.journalDialogVisible=false;
              this.load();
            }else{
              this.$message.error(res.msg);
            }
          })
        }
      })
    },
    formattedDate() {
      // 将currentDate转换为指定格式的字符串
      return moment(this.date).format('YYYY-MM-DD');
    },
    yesterdayLoad(){
      this.date.setDate(this.date.getDate() - 1);
      this.load();
    },
    tomorrowLoad(){
      this.date.setDate(this.date.getDate() + 1);
      this.load();
    },
    querySearch (queryString, cb){ //queryString是需要查询的参数，也可以为空；cb是需要回调的方法，用来把列表传给组件
      console.log("querySearch:"+queryString)
      cb(this.typeList)
    },
    createFilter(queryString){
      console.log("createFilter:"+queryString)
    },
  }
}
</script>
<style>
.cell {
  white-space: pre-line !important;
}

</style>